<?php


namespace app\middleware;

use app\lib\exception\AuthException;
use app\utils\JWT;
use think\facade\Cache;

class JwtAuth
{
    public function handle($request, \Closure $next)
    {
        $token = JWT::getRequestToken();
        if (empty($token))
        {
            throw  new AuthException();
        }

        $result = JWT::parse($token);

        $userInfo = Cache::store('redis')->get($token);

        if (empty($userInfo))
        {
            throw  new AuthException();
        }

        if ($userInfo['id'] != $result)
        {
            throw  new AuthException();
        }

//      验证通过,将得到的用户id,放到请求信息中去,方便后续使用
        $request->id = $result;

        return $next($request);
    }

    public function end(\think\Response $response)
    {
        $token = JWT::getRequestToken();
        Cache::store('redis')->expire($token,config('jwt.exp'));
    }

}